//
//  BwtSplashAd.m
//  bwt_ad_flutter
//
//  Created by ciba on 2024/8/30.
//

#import "BwtSplashAd.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
#import "CXHAdSDK-Core/CXHAdSDKSplashAd.h"
#import "BwtSplashAdManager.h"
#import "BwtAdLogManager.h"

#if __has_include(<CXHAdSDK-Kit/CXHUtilsKit.h>)
#import <CXHAdSDK-Kit/CXHUtilsKit.h>
#else

#endif

@interface BwtSplashAd () <CXHAdSDKSplashAdDelegate>

@property(nonatomic, strong) CXHAdSDKSplashAd *splashAd;

@property(nonatomic) bool isAdClosed;

@property(nonatomic) bool isAdExposed;

@end

@implementation BwtSplashAd

- (void)loadSplashAd {
    if (self.splashAd) {
        return;
    }
    [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告加载前检查, adId: %@", _adParams.adId];
    if (_isRequestIdfa && @available(iOS
    14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(
                ATTrackingManagerAuthorizationStatus status) {
            if ([NSThread isMainThread]) {
                [self innerLoadSplashAd];
            } else {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // 非主线程，将UI操作切换到主线程进行，请求广告
                    [self innerLoadSplashAd];
                });
            }
        }];
    } else {
        [self innerLoadSplashAd];
    }
}

- (void)innerLoadSplashAd {
    if (self.splashAd) {
        return;
    }

    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIViewController *rvc = window.rootViewController;

    self.splashAd = [[CXHAdSDKSplashAd alloc] init];
    self.splashAd.showTime = 5;
    self.splashAd.delegate = self;
    self.splashAd.controller = rvc;
    self.splashAd.setSkipButtonToRightTop = YES;
    self.splashAd.posId = _adParams.posId;

    NSString *adBackground = _adParams.adBackground;
    if (adBackground) {
        // 设置默认启动图(一般设置启动图的平铺颜色为背景颜色，使得视觉效果更加平滑)
        self.splashAd.backgroundImage = [UIImage imageNamed:adBackground];
    }

    // 构建底部logo控件
    UIView *bottomView = [self getBottomView:0];
    if (bottomView) {
        self.splashAd.bottomView = bottomView;
    }

    [[BwtAdLogManager getBwtAdLogManager] log:@"正在加载开屏广告, adId: %@", _adParams.adId];
    
    /// 加载开屏广告
    [self.splashAd loadSplashAd];
    
}

#pragma mark - CXHAdSDKSplashAdDelegate

/**
 开屏广告点击回调, 可能会打开 AppStore, WebView, ThirdApp etc.

 @param splashAd 开屏广告
 @param loadingPageURL 广告落地页地址，当渠道为bwt，并且customLoadingPage为YES时有值
 */
- (void)CXH_splashAdDidClick:(CXHAdSDKSplashAd *)splashAd loadingPageURL:(NSString *)loadingPageURL {
    [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告被点击, adId: %@", _adParams.adId];
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdClickEvent:_adParams];
}

/**
 开屏广告关闭回调, 触发条件: 点击广告, 点击跳过, 超时关闭

 @param splashAd 开屏对象
 */
- (void)CXH_splashAdDidClose:(CXHAdSDKSplashAd *)splashAd {
    [self closeAd];
}

/**
 开屏广告曝光回调

 @param splashAd 开屏对象
 */
- (void)CXH_splashAdExposured:(CXHAdSDKSplashAd *)splashAd {
    if (!self.isAdExposed) {
        [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告被曝光, adId: %@", _adParams.adId];
        self.isAdExposed = YES;
        /// 通知Flutter端
        BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
        [bwtAdEventManager postOnAdExposeEvent:_adParams];
    }
}

/**
 开屏广告加载成功
 
 @param splashAd 开屏对象
 */
- (void)CXH_splashAdDidLoad:(CXHAdSDKSplashAd *)splashAd {
    if ([self.splashAd isAdValid]) {
        [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告加载成功，开始展示到 Window, adId: %@", _adParams.adId];
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [self.splashAd showSplashAdInWindow:window];
    } else {
        [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告加载异常, adId: %@, error: %@", _adParams.adId, @"开屏广告已被销毁"];
        /// 通知Flutter端
        BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
        [bwtAdEventManager postOnAdLoadFailedEvent:_adParams message:@"开屏广告已被销毁"];
        
        [self closeAd];
    }
}

/**
 开屏广告加载失败
 
 @param splashAd 开屏对象
 */
- (void)CXH_splashAdDidFailToLoad:(CXHAdSDKSplashAd *)splashAd error:(NSError *)error {
    NSString *message = [error localizedDescription];
    
    [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告加载失败, adId: %@, error: %@", _adParams.adId, message];
    
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdLoadFailedEvent:_adParams message:message];

    [self closeAd];
}

/**
 *  开屏广告成功展示
 *
 *  @param splashAd 开屏对象
 */
- (void)CXH_splashAdSuccessPresentScreen:(CXHAdSDKSplashAd *)splashAd {
    [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告成功展示, adId: %@", _adParams.adId];
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdLoadEvent:_adParams];
}

/**
 *  开屏广告展示失败
 *
 *  @param splashAd 开屏对象
 */
- (void)CXH_splashAdFailToPresent:(CXHAdSDKSplashAd *)splashAd withError:(NSError *)error {
    NSString *message = [error localizedDescription];
    
    [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告展示失败, adId: %@, error: %@", _adParams.adId, message];
    
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdLoadFailedEvent:_adParams message:message];
    
    [self closeAd];
}

/**
 *  开屏广告关闭落地页
 *
 *  @param splashAd 开屏对象
 */
- (void)CXH_splashAdCloseLandingPage:(CXHAdSDKSplashAd *)splashAd {

}

/// 关闭开屏广告
- (void)closeAd {
    if (!self.isAdClosed) {
        self.isAdClosed = YES;
        self.splashAd = nil;
        
        [[BwtAdLogManager getBwtAdLogManager] log:@"开屏广告被关闭, adId: %@", _adParams.adId];
        
        BwtSplashAdManager *bwtSplashAdManager = [BwtSplashAdManager getBwtSplashAdManager];
        [bwtSplashAdManager releaseAd:_adParams.adId];

        /// 通知Flutter端
        BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
        [bwtAdEventManager postOnAdCloseEvent:_adParams];
    }
}


- (UIView *)getBottomView:(CGFloat)bottomViewOffY {
    NSString *adLogo = _adParams.adLogo;

    if (adLogo) {
        UIImage *logoImage = [UIImage imageNamed:adLogo];
        if (logoImage) {
            // 开屏广告机型适配
            CGFloat bottomViewHeight = 156;

            // 底部视图设置
            UIView *bottomView = [[UIView alloc] init];
            bottomView.backgroundColor = [UIColor whiteColor];
            bottomView.frame = CGRectMake(0, bottomViewOffY,
                                          [UIScreen mainScreen].bounds.size.width,
                                          bottomViewHeight);

            CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
            CGFloat logoWidth = logoImage.size.width * 92 / logoImage.size.height;
            if (logoWidth > screenWidth - 32) {
                logoWidth = screenWidth - 32;
            }

            UIImageView *logoImageView = [[UIImageView alloc] initWithImage:logoImage];
            logoImageView.frame = CGRectMake(
                    ([UIScreen mainScreen].bounds.size.width - logoWidth) / 2,
                    (bottomViewHeight - 92) / 2, logoWidth, 92);
            [bottomView addSubview:logoImageView];

            return bottomView;
        }
    }

    return nil;
}
@end
